package main

import (
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"

	_ "net/http/pprof"
)

var (
	fileurl  = "/file/"
	filePath = "."
	port     = "8080"
)

func main() {
	if len(os.Args) > 1 {
		if os.Args[1] == "-h" || os.Args[1] == "help" {
			usage()
			os.Exit(1)
		}
		parseArg()
	}
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "<h1>您好，欢迎使用。</h1>")
	})

	http.Handle(fileurl, http.StripPrefix(fileurl, http.FileServer(http.Dir(filePath))))

	fmt.Println("Server listen at :" + port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}

func usage() {
	msg := `使用说明：
示例：%s port=8080 fileurl=/file/ root=.
    port: 监听的端口
    fileurl: url中访问静态文件服务器的路径
    root:  指定文件路径的根目录
`
	fmt.Printf(msg, os.Args[0])
}

func parseArg() {
	n := len(os.Args)
	for i := 1; i < n; i++ {
		arg := os.Args[i]
		fmt.Println(arg)
		list := strings.Split(arg, "=")
		if len(list) != 2 {
			fmt.Println(arg, "未生效")
			continue
		}
		opt := list[0]
		val := list[1]
		// opt, val := strings.Split(arg, "=")
		switch opt {
		case "port":
			port = val
		case "fileurl":
			fileurl = val
		case "root":
			filePath = val
		default:
			fmt.Println(arg, "未生效")
		}
	}
}
